import os
import json
import argparse

import yaml
import opencc

OPTIONS = None

COLOR_MAP = {
    'grey'   : '\033[30m',
    'red'    : '\033[31m',
    'green'  : '\033[32m',
    'yellow' : '\033[33m',
    'blue'   : '\033[34m',
    'magenta': '\033[35m',
    'cyan'   : '\033[36m',
}
def colored(s, color=None):
    if not color:
        color = 'yellow'

    color = COLOR_MAP[color]

    return color + '{}\033[0m'.format(s)

def get_options_by_command_line():
    global OPTIONS

    arg_parser = argparse.ArgumentParser(description='Traditional Chinese Translation Generator')

    args = vars(arg_parser.parse_args())
    args = dict(filter(lambda x: x[1] is not None, args.items()))

    OPTIONS = args

BASE_PATH_VUE = 'client/src'

FILE_PATH_ZH_CN_SRC_PATTERNS = [
    'client/src/assets/yaml/locales.{}.yaml',
    'client/src/assets/yaml/messages.{}.yaml',
    'server/statics/yaml/setup-locals.{}.yaml',
    'script-example/example.{}.py',
]

LOCALE_CONVERTER_MAP = {
    'zh-HK': opencc.OpenCC('s2hk.json'),
    'zh-TW': opencc.OpenCC('s2twp.json'),
}

VUE_I18N_ZH_CN_START_LINE  = '<i18n locale="zh-CN" lang="yaml">'
VUE_I18N_ZHT_START_PATTERN = '<i18n locale="{}" lang="yaml">'
VUE_I18N_END_LINE          = '</i18n>'
VUE_GEN_START_LINE         = '<!-- Generated by OpenCC START -->'
VUE_GEN_END_LINE           = '<!-- Generated by OpenCC END -->'

def print_debug_info(f):
    print(f"Generating zht language for {f.split('/')[-1]}")

def get_file_list(base_path, ext, no_ext=None):
    file_list = []

    for root, dirs, files in os.walk(base_path):
        for file in files:
            if not file.endswith(ext):
                continue

            if no_ext and file.endswith(no_ext):
                continue

            file_path = os.path.join(root, file)
            file_list.append(file_path)

    return file_list

def gen_zht_to_vue():
    file_list = get_file_list(BASE_PATH_VUE, ext='.vue')
    for f in file_list:
        print_debug_info(f)

        with open(f, 'r') as _f:
            file_content = _f.read()
            prev_file_lines = file_content.splitlines()

            # Skip files no need translation
            if VUE_I18N_ZH_CN_START_LINE not in prev_file_lines:
                continue

            # Clear prev translation
            start_index = None
            end_index   = None
            for i, l in enumerate(prev_file_lines):
                if l.strip() == VUE_GEN_START_LINE:
                    if i > 0 and prev_file_lines[i - 1].strip() == '':
                        start_index = i - 1
                    else:
                        start_index = i
                    continue

                if start_index and l.strip() == VUE_GEN_END_LINE:
                    end_index = i + 1
                    break

            if start_index and end_index:
                file_lines = prev_file_lines[0:start_index] + prev_file_lines[end_index:]
            else:
                file_lines = prev_file_lines

            # Pick zh-CN parts
            start_index = None
            end_index   = None
            zh_cn_lines = []
            for i, l in enumerate(file_lines):
                if l.strip() == VUE_I18N_ZH_CN_START_LINE:
                    start_index = i + 1
                    continue

                if start_index and l.strip() == VUE_I18N_END_LINE:
                    end_index = i
                    break

                if start_index is not None and end_index is None:
                    zh_cn_lines.append(l)

            zh_cn_yaml = '\n'.join(zh_cn_lines)
            zh_cn = yaml.safe_load(zh_cn_yaml)

            zht_lines = [ '', VUE_GEN_START_LINE ]
            for locale, converter in LOCALE_CONVERTER_MAP.items():
                converted = {}
                for k, v in zh_cn.items():
                    converted[k] = converter.convert(v)

                zht_lines.append(VUE_I18N_ZHT_START_PATTERN.format(locale))
                zht_lines.append(yaml.dump(converted, allow_unicode=True, width=9999, line_break=False).strip())
                zht_lines.append(VUE_I18N_END_LINE)

            zht_lines.append(VUE_GEN_END_LINE)

            zht = '\n'.join(zht_lines)
            file_lines.insert(end_index + 1, zht)

        # Write to source file
        with open(f, 'w') as _f:
            output = '\n'.join(file_lines)
            _f.write(output.rstrip() + '\n')

def gen_zht_from_zh_cn():
    for pattern in FILE_PATH_ZH_CN_SRC_PATTERNS:
        src_file_path = pattern.format('zh-CN')
        print_debug_info(src_file_path)

        for locale, converter in LOCALE_CONVERTER_MAP.items():
            output_path = pattern.format(locale)

            src_file_content = None
            with open(src_file_path, 'r') as _f:
                src_file_content = _f.read()

            if src_file_path.endswith('.yaml'):
                src_file_content = yaml.safe_load(src_file_content)

                converted = { }
                for k, v in src_file_content.items():
                    converted[k] = converter.convert(v)

                with open(output_path, 'w') as _f:
                    output = f'# Generated by {__file__} with OpenCC\n\n' + yaml.dump(converted, allow_unicode=True, width=9999)
                    _f.write(output)

            else:
                converted = converter.convert(src_file_content)
                with open(output_path, 'w') as _f:
                    output = f'# Generated by OpenCC\n\n' + converted
                    _f.write(output)

def main():
    get_options_by_command_line()

    gen_zht_to_vue()
    gen_zht_from_zh_cn()

if __name__ == '__main__':
    print(colored('Gen zht Language', 'green'))
    main()
    print(colored('Done', 'green'))
